<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input v-model="queryParams.taskName" placeholder="请输入任务名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否关闭" prop="status">
        <el-select v-model="queryParams.closed" placeholder="是否关闭" clearable size="small" style="width: 90px" >
          <el-option v-for="dict in closedOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['business:task:add']" >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['business:task:edit']" >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['business:task:remove']" >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['business:task:export']" >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-open" size="mini" @click="openTask" >开启任务</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-turn-off" size="mini" @click="closeTask" >关闭任务</el-button>
      </el-col>
	    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务id" align="center" prop="id" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务金额" align="center" prop="taskPrice" />
      <el-table-column label="任务数量" align="center" prop="taskNum" />
      <el-table-column label="排序权重" align="center" prop="sort" />
      <el-table-column label="是否关闭" align="center" prop="closed" :formatter="closedFormatter"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务金额" prop="taskPrice">
          <el-input-number v-model="form.taskPrice" :min="0" placeholder="请输入任务金额" />
        </el-form-item>
        <el-form-item label="任务数量" prop="taskNum">
          <el-input-number v-model="form.taskNum" :min="0" placeholder="请输入任务数量" />
        </el-form-item>
        <el-form-item label="任务步骤" prop="taskStep">
          <el-button v-model="form.taskStep" :type="taskStepButtonType" :icon="taskStepButtopIcon" @click="addTaskStep">{{taskStepButtonTitle}}</el-button>
        </el-form-item>
        <el-form-item label="排序权重" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="100" placeholder="请输入排序权重" />
        </el-form-item>
        <el-form-item label="是否关闭" prop="status">
          <el-select v-model="queryParams.closed" placeholder="默认为开启" clearable size="small" style="width: 120px" >
            <el-option v-for="dict in closedOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  添加任务步骤弹出框  -->
    <el-dialog :title="title" :visible.sync="taskStepDialog" width="500px" append-to-body>
      <el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="60px" class="demo-dynamic">
        <el-form-item
          v-for="(domain, index) in dynamicValidateForm.domains"
          :label="'步骤' + index"
          :key="domain.key"
          :prop="'domains.' + index + '.stepText'"
          :rules="{required: true, message: '步骤不能为空', trigger: 'blur'}">
          <el-button style="padding: 5px; margin-bottom: 2px" type="danger" @click.prevent="removeDomain(domain)">删除步骤{{ index }}</el-button>
          <el-input autosize type="textarea" v-model="domain.stepText"></el-input>
          <el-upload
            v-model="domain.stepImage"
            class="upload-demo"
            drag
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将任务步骤图片拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addTaskStepSave('dynamicValidateForm')">提交</el-button>
          <el-button @click="addDomain">新增步骤</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, exportTask, operateTask ,uploadTaskStepImage } from "@/api/business/task";
import store from "@/store";

export default {
  name: "Task",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务表格数据
      taskList: [],
      // 是否删除字典
      deletedOptions: [],
      // 是否关闭字典
      closedOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示添加任务步骤弹出层
      taskStepDialog: false,

      // 按钮文字
      taskStepButtonTitle: '点击添加任务步骤',
      // 按钮样式
      taskStepButtonType: 'primary',
      // 按钮图标
      taskStepButtopIcon: 'el-icon-circle-plus-outline',

      active: 0,

      dynamicValidateForm: {
        domains: [{
          stepText: '',
          stepImage: '',
          url: '',
        }]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        deleted: null,
        sort: null,
        closed: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        taskPrice: [
          { required: true, message: "任务金额不能为空", trigger: "blur" }
        ],
        taskNum: [
          { required: true, message: "任务数量不能为空", trigger: "blur" }
        ],
        taskStep: [
          { required: true, message: "任务步骤不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序权重不能为空", trigger: "blur" }
        ],
        closed: [
          { required: true, message: "是否关闭不能为空", trigger: "blur" }
        ],
      },
      options: {
        img: store.getters.avatar, //裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 200, // 默认生成截图框宽度
        autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: true // 固定截图框大小 不允许改变
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("closed").then(response => {
      this.closedOptions = response.data;
    });
  },
  methods: {
    /** 查询任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    closedFormatter(row){
      return this.selectDictLabel(this.closedOptions, row.closed)
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskName: null,
        taskPrice: null,
        taskNum: null,
        taskStep: null,
        deleted: null,
        sort: null,
        closed: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改任务";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              if (response.code === 200){
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }else {
                this.msgError("修改失败, 请联系管理员");
              }
            });
          } else {
            addTask(this.form).then(response => {
              if (response === 200){
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }else {
                this.msgSuccess("新增失败, 请联系管理员");
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除任务编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTask(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有任务数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportTask(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
    /** 开启任务 */
    openTask(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否开启任务编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return operateTask(ids, 0);
      }).then(() => {
        this.getList();
        this.msgSuccess("开启成功");
      })
    },
    /** 关闭任务 */
    closeTask(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否关闭任务编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return operateTask(ids, 1);
      }).then(() => {
        this.getList();
        this.msgSuccess("关闭成功");
      })
    },
    /*添加任务步骤*/
    addTaskStep(){
      this.taskStepDialog = true;
    },
    addTaskStepSave(){
      this.taskStepDialog = false;
      this.taskStepButtonTitle = '已添加任务步骤';
      this.taskStepButtonType = 'success';
      this.taskStepButtopIcon = 'el-icon-circle-check';
      this.form.taskStep = JSON.stringify(this.dynamicValidateForm);
      console.log(this.dynamicValidateForm)
    },
    /*添加任务步骤下一步*/
    removeDomain(item) {
      var index = this.dynamicValidateForm.domains.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.domains.splice(index, 1)
      }
    },
    addDomain() {
      this.dynamicValidateForm.domains.push({
        value: '',
        key: Date.now()
      });
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    beforeUpload(file) {
      if (file.type.indexOf("image/") === -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      }
    },
  }
};
</script>
